package br.usp.ime.ingpos.services;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.core.Localization;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.usp.ime.ingpos.modelo.Email;
import br.usp.ime.ingpos.modelo.Usuario;
import br.usp.ime.ingpos.modelo.dao.UsuarioDao;
import br.usp.ime.ingpos.seguranca.Criptografia;

@RequestScoped
@Component
public class SenhaService
{

    private final UsuarioDao usuarioDao;
    private final EmailService emailService;
    private final Localization localization;
    private final HttpServletRequest httpServletRequest;

    public SenhaService(
        final UsuarioDao usuarioDao,
        final EmailService emailService,
        final Localization localization,
        final HttpServletRequest httpServletRequest )
    {
        this.usuarioDao = usuarioDao;
        this.emailService = emailService;
        this.localization = localization;
        this.httpServletRequest = httpServletRequest;
    }

    private String getUrlLogin()
    {
        if( httpServletRequest != null ) {
            final String url = httpServletRequest.getRequestURL().toString();
            if( url.endsWith( "/forgot" ) )
                return url.substring( 0, url.lastIndexOf( "/forgot" ) );
        }
        return "http://localhost:8080/Ingresso-na-Pos/login/";
    }

    public boolean atualizarSenha(
        final String email,
        final String novaSenha )
    {
        final Usuario usuario = usuarioDao.procurarPorEmail( email );

        if( usuario != null ) {
            usuario.setSenha( Criptografia.md5( novaSenha ) );
            usuarioDao.saveOrUpdate( usuario );
            return true;
        } else {
            return false;
        }
    }

    public boolean enviarEmailSucedido(
        final String email )
    {
        try {
            final Usuario usuario = usuarioDao.procurarPorEmail( email );

            if( usuario != null ) {

                emailService.enviarEmail( construirEmailTrocaSenha( usuario ) );

                return true;
            } else {
                return false;
            }
        } catch( EmailException e ) {
            return false;
        }
    }

    private Email construirEmailTrocaSenha(
        final Usuario usuario )
    {
        final StringBuilder linkBuilder = new StringBuilder();
        linkBuilder.append( getUrlLogin() );
        linkBuilder.append( "/resetarSenha/" + usuario.getHash() );

        final String assunto = localization.getMessage( "senha_email_assunto" );
        final String conteudo = localization.getMessage( "senha_email_conteudo", usuario.getDadosPessoais().getNomeCompleto(), linkBuilder.toString());

        return emailService.construirEmail( assunto, conteudo+localization.getMessage( "email_rodape"), usuario.getEmail() );
    }
    
    public boolean isMatchByMD5WithCriptografada(String senha, String criptografada) {
        return (Criptografia.md5( senha ).equals( criptografada ));
    }
}